﻿using DynamicPatcher;
using Extension.Decorators;
using Extension.Ext;
using Extension.Utilities;
using PatcherYRpp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Extension.MyExtension.InternalComponents
{
    public class VirtualTurretComponent : EventDecorator
    {
        public static DecoratorId ID = new DecoratorId(12306001);

        public VirtualTurretComponent(TechnoExt self,TechnoExt parent, CoordStruct flh)
        {
            Self.Set(self);
            Parent.Set(parent);
            FLH = flh;
        }

        ExtensionReference<TechnoExt> Parent;
        ExtensionReference<TechnoExt> Self;
        private CoordStruct FLH;

        public override void OnUpdate()
        {
            TechnoExt selfExt;
            if(!Self.TryGet(out selfExt))
            {
                Logger.Log("子单位没了");
                Decorative.Remove(this);
                return;
            }
            TechnoExt parentExt;
            if (!Parent.TryGet(out parentExt))
            {
                Logger.Log("父单位没了");
                Decorative.Remove(this);
                selfExt.OwnerObject.Ref.Base.Remove();
                selfExt.OwnerObject.Ref.Base.UnInit();
                return;
            }

            if(parentExt.OwnerObject.Ref.Base.IsOnMap)
            {
                Logger.Log("父单位在地图上");

                var targetLocation = parentExt.OwnerObject.Ref.Base.Base.GetCoords();
                if (selfExt.OwnerObject.Ref.Base.IsOnMap == false)
                {
                    Logger.Log("炮塔未在地图上");
                    if (!selfExt.OwnerObject.Ref.Base.Put(targetLocation + FLH, Direction.N))
                        return;
                }
                Logger.Log("设置炮塔坐标");
                selfExt.OwnerObject.Ref.Base.SetLocation(targetLocation);
            }
            else
            {
                Logger.Log("父单位不在地图上");

                if (selfExt.OwnerObject.Ref.Base.IsOnMap == true)
                {
                    Logger.Log("子单位在地图上，移除子单位");
                    selfExt.OwnerObject.Ref.Base.InLimbo = false;
                }
            }

            base.OnUpdate();
        }

    }



}
